<template>
    <div class="container-fluid" v-loading="loading">


        <div class="row">
            <div class="col-lg-12">
                <div class="card">

                    <div class="card-header">
                        {{ companyName }}
                        &nbsp;&nbsp; <el-button size="mini" type="danger" v-if="status===1" @click="handleSetStatus(companyId,0)">停用</el-button>
                        <el-button size="mini" type="success" v-if="!status" @click="handleSetStatus(companyId,1)">开启</el-button>
                    </div>

                    <div class="card-toolbar clearfix">
                        <form class="form-inline" onsubmit="return false;">
                            <div class="form-group">
                                <label>公司别名</label>
                                <el-tag
                                        :key="tag"
                                        v-for="tag in alternativeName"
                                        closable
                                        :disable-transitions="false"
                                        @close="handleClose(tag)">
                                    {{tag}}
                                </el-tag>
                                <el-input
                                        class="input-new-tag"
                                        v-if="inputVisible"
                                        v-model="inputValue"
                                        ref="saveTagInput"
                                        @keyup.enter.native="handleInputConfirm"
                                        @blur="handleInputConfirm"
                                        style="width: 40%;"
                                >
                                </el-input>
                                <el-button v-else class="button-new-tag" size="small" @click="showInput">+ 添加公司别称
                                </el-button>
                            </div>

                            <div class="form-group">
                                <label>所属分类</label>
                                <el-autocomplete
                                        v-model="categoryName"
                                        :fetch-suggestions="querySearchAsync"
                                        placeholder="请输入内容"
                                        @select="handleSelect"
                                ></el-autocomplete>
                                <el-tag
                                        :key="tag.id"
                                        v-for="tag in categoryTags"
                                        closable
                                        :disable-transitions="false"
                                        @close="handleIndustryClose(tag)">
                                    {{tag.value}}
                                </el-tag>
                            </div>

                        </form>
                    </div>
                    <company-menu-components :company-id="companyId" :active-index="activeIndex"></company-menu-components>

                    <div class="card-body">
                        <div class="table-responsive" style="width: 100%;margin-top: 20px;" v-loading="loading">
                            <el-table
                                    :data="list"
                                    style="width: 100%"
                                    @sort-change='sortChange'
                                    :default-sort="{prop: '_id', order: 'descending'}"
                            >
                                <el-table-column
                                        label="ID"
                                        type="index"
                                        :index="indexMethod"
                                        width="40">
                                </el-table-column>
                                <el-table-column
                                        prop="title"
                                        label="文章标题"
                                        align="center"
                                        width="160">
                                    <template slot-scope="scope">
                                        <a :href="'/admin/article/'+scope.row._id+'/edit'" target="_blank" style="cursor:pointer;">{{scope.row.title
                                            }}</a>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                        prop="userName"
                                        label="上传用户"
                                        align="center"
                                        width="80">
                                </el-table-column>
                                <el-table-column
                                        prop="companyStr"
                                        label="所属公司"
                                        align="center"
                                        width="100">
                                </el-table-column>
                                <el-table-column
                                        prop="categoryStr"
                                        label="所属分类"
                                        align="center"
                                        width="70">
                                </el-table-column>
                                <el-table-column
                                        prop="officialAccount"
                                        label="来源公众号"
                                        align="center"
                                        width="120">
                                </el-table-column>
                                <el-table-column
                                        prop="created_at"
                                        label="上传时间"
                                        align="center"
                                        sortable
                                        width="170">
                                </el-table-column>
                                <el-table-column
                                        label="操作"
                                        align="center"
                                >
                                    <template slot-scope="scope">
                                        <span class="span-success" @click="handleEdit(scope.row,1)">通过</span>
                                        <span class="span-success" @click="handleEdit(scope.row,-1)">不通过</span>
                                        <span class="span-danger" @click="handleDelete(scope.row)">删除</span>
                                        <a v-if="scope.row.originalUrl" :href="scope.row.originalUrl"
                                           target="_bland">原文</a>
                                    </template>

                                </el-table-column>
                            </el-table>

                            <nav style="margin-top: 20px">
                                <el-pagination
                                        layout="total, sizes, prev, pager, next, jumper"
                                        :total="total"
                                        :hide-on-single-page="pageActive"
                                        @size-change="handleSizeChange"
                                        :page-size="pageSize"
                                        :current-page="currentPage"
                                        :page-sizes="[10, 20, 30, 40]"
                                        @current-change="handleCurrentChange"
                                >
                                </el-pagination>

                            </nav>

                            <el-dialog title="文章审核" :visible.sync="dialogFormVisible" :close-on-click-modal="false">
                                <el-form :model="form">

                                    <el-form-item label="" :label-width="formLabelWidth">
                                        <h5>{{articleTitle}}</h5>
                                    </el-form-item>


                                    <el-form-item label="关联分类" :label-width="formLabelWidth">
                                        <el-autocomplete
                                                v-model="form.categoryName"
                                                :fetch-suggestions="querySearchAsync"
                                                placeholder="请输入内容"
                                                @select="handleQuerySelect"
                                                style="width: 100%"
                                        ></el-autocomplete>
                                        <el-tag
                                                :key="tag.id"
                                                v-for="tag in categoryTags"
                                                closable
                                                :disable-transitions="false"
                                                @close="handleIndustryClose(tag)">
                                            {{tag.value}}
                                        </el-tag>
                                    </el-form-item>

                                    <el-form-item label="关联公司" :label-width="formLabelWidth">
                                        <el-autocomplete
                                                v-model="form.companyName"
                                                :fetch-suggestions="queryCompanyAsync"
                                                placeholder="请输入内容"
                                                @select="handleCompanySelect"
                                                style="width: 100%"
                                        ></el-autocomplete>
                                        <el-tag
                                                :key="tag.id"
                                                v-for="tag in companyTags"
                                                closable
                                                :disable-transitions="false"
                                                @close="handleCompanyClose(tag)">
                                            {{tag.value}}
                                        </el-tag>
                                    </el-form-item>
                                </el-form>
                                <div slot="footer" class="dialog-footer">
                                    <el-button @click="dialogFormVisible = false">取 消</el-button>
                                    <el-button type="primary" @click="submitSet">{{ verifyName }}</el-button>
                                </div>
                            </el-dialog>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
    import CompanyMenuComponents from "./CompanyMenuComponents";
    export default {
        name: "CompanyArticleVerifyComponent",
        components: {
            "company-menu-components": CompanyMenuComponents,
        },
        data() {
            return {
                pageActive: false,
                list: [],
                pageSize: 10,
                total: 0,
                currentPage: 1,
                loading: true,
                activeIndex: "6",
                form: {
                    name: '',
                    categoryName: '',
                    companyName: ''
                },
                categoryTags: [],
                categoryIds: [],
                companyTags: [],
                companyIds: [],
                dialogFormVisible: false,
                formLabelWidth: '120px',
                companies: [],
                restaurants: [],
                id: 0,
                order: 'desc',
                orderField: '_id',
                articleTitle: '',
                verifyName: '确 定',
                verifyStatus: 1,
                companyId: $('meta[name="id"]').attr('content'),
                //公司部分
                alternativeName: [],
                categoryName: '',
                inputVisible: false,
                inputValue: '',
                companyName:'',
                status:0,
            }
        },
        methods: {

            getInfo() {
                let self = this;
                let uri = "company/" + self.companyId;
                self.loading = true;

                axios.get(uri,function (data) {
                    let result = data.result;
                    self.companyName = result.name;
                    self.status = 0;
                    self.status = result.status;
                    self.categoryIds = [];
                    self.categoryTags = [];
                    self.alternativeName = [];
                    self.alternativeName = result.alternativeName;
                    self.categoryTags = result.categoryNames;
                    result.categoryNames.forEach((item) => {
                        self.categoryIds.push(item.id)
                    });
                    self.loading = false;
                },function (error) {
                    self.loading = false;
                });
            },

            search: function () {
                let self = this;
                let uri = 'article/post-list';
                self.loading = true;
                let postData = {
                    startTime: self.startTime, endTime: self.endTime,
                    keyword: self.keyword,
                    page: self.currentPage,
                    limit: self.pageSize,
                    status: self.status,
                    order: self.order,
                    orderField: self.orderField,
                    verifyStatus: 0,
                    //companyId: self.companyId

                };
                axios.post(uri, postData).then(function (result) {
                    self.total = result.articles.total;
                    if (self.total > 0) {
                        self.pageActive = false;
                    } else {
                        self.pageActive = true;
                    }
                    self.list = result.articles.data;
                    self.loading = false;
                }).cathe(function (error) {
                    self.loading = false;
                });
            },
            handleSizeChange: function (pageSize) {
                this.pageSize = pageSize;
                this.search();
            },
            handleCurrentChange: function (val) {
                this.currentPage = val;
                this.search();
            },
            indexMethod: function (index) {
                return index + 1;
            },
            formatTitle: function (row, column) {
                return this.filterLength(row.title, 10);
            },
            filterLength: function (str, length = 9) {
                if (str.length >= length) {
                    return str.substring(0, length) + '...';
                }
                return str.length === 0 ? '--' : str;
            }, formatCompany: function (row, column) {
                return this.filterLength(row.companyStr, 4);
            },
            async queryIndustry(keyword = '') {
                let self = this;
                let uri = "category/search/" + keyword;
                axios.get(uri).then(function (result) {
                    self.restaurants = result.list;
                });
            },
            async queryCompany(keyword = '') {
                let self = this;
                let uri = "company/search/" + keyword;
                axios.get(uri).then(function (result) {
                    self.companies = result.list;
                });
            },
            async querySearchAsync(queryString, cb) {
                await this.queryIndustry(queryString);

                var restaurants = this.restaurants;
                var results = queryString ? restaurants.filter(this.createStateFilter(queryString)) : restaurants;

                clearTimeout(this.timeout);
                this.timeout = setTimeout(() => {
                    cb(results);
                }, 3000 * Math.random());

            },
            handleQuerySelect(item) {
                if (item && this.categoryIds.indexOf(item.id) === -1) {
                    this.categoryTags.push(item);
                    this.categoryIds.push(item.id);
                }
                this.form.categoryName = '';
            },
            async queryCompanyAsync(queryString, cb) {
                await this.queryCompany(queryString);
                var restaurants = this.companies;
                var results = queryString ? restaurants.filter(this.createStateFilter(queryString)) : restaurants;
                clearTimeout(this.timeout);
                this.timeout = setTimeout(() => {
                    cb(results);
                }, 1000 * Math.random());
            },
            handleCompanySelect(item) {
                if (item && this.companyIds.indexOf(item.id) === -1) {
                    this.companyTags.push(item);
                    this.companyIds.push(item.id);
                }
                this.form.companyName = '';
            },
            handleIndustryClose(tag) {
                this.categoryTags.splice(this.categoryTags.indexOf(tag), 1);
                this.categoryIds.splice(this.categoryIds.indexOf(tag.id), 1);
            },
            handleCompanyClose(tag) {
                this.companyTags.splice(this.companyTags.indexOf(tag), 1);
                this.companyIds.splice(this.companyIds.indexOf(tag.id), 1);
            },
            handleEdit(row, verify) {
                let self = this;

                self.verifyStatus = verify;

                if (verify === 1) {
                    self.verifyName = "保存并通过审核";
                } else {
                    self.verifyName = "保存并不通过审核";
                }
                self.dialogFormVisible = true;
                self.form.categoryName = '';
                self.form.companyName = '';
                self.companyIds = [];
                self.companyTags = [];
                self.categoryIds = [];
                self.categoryTags = [];
                self.articleTitle = row.title;
                self.categoryTags = row.categoryNames;

                row.categoryNames.forEach((item) => {
                    self.categoryIds.push(item.id)
                });
                self.companyTags = row.companies;
                row.companies.forEach((item) => {
                    self.companyIds.push(item.id)
                });
                self.id = row._id;
            },
            sortChange(item) {
                let order = "asc";
                this.orderField = item.prop;
                if (item.order === 'descending') {
                    order = "desc";
                }
                this.order = order;
                this.search();
            },
            openEdit(id) {
                //this.openUri('article/' + id + '/edit');
                window.href.location = '/admin/article/' + id + '/edit'
            },
            handleDelete: function (row) {
                let self = this;
                let tipStr = "此操作将永久删除“" + row.title + "”, 是否继续?";
                self.$confirm(tipStr, '文章删除', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    self.deleteRequire(row._id)
                }).catch(() => {
                    self.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
            },
            deleteRequire: function (id) {
                let self = this;
                let uri = "article/" + id;
                self.loading = true;
                axios.delete(uri).then(function (result) {
                    self.search();
                }).catch(function (error) {
                    self.loading = false;
                });
            },
            submitSet() {
                let self = this;
                let categoryIds = this.categoryIds;
                let companyIds = this.companyIds;

                /*if (categoryIds.length > 0 && companyIds.length > 0) {
                    self.$message.error('不能同时选择分类和公司！');
                    return;
                }*/
                self.loading = true;
                let uri = "article/set/" + self.id;
                let data = {companyIds: companyIds, categoryIds: categoryIds, verifyStatus: self.verifyStatus};

                if (self.verifyStatus == 1){
                    data.status = 1;
                }

                self.dialogFormVisible = false;

                axios.put(uri, data).then(function (result) {
                    self.search();
                }).catch(function () {
                    self.loading = false;
                });
            },
            //公司开始
            handleSetStatus(id,status){
                let self = this;
                let uri = "company/set-status/" + id + "/" + status;
                axios.get(uri).then(function (data) {
                    self.getInfo();
                });
            },
            showInput() {
                this.inputVisible = true;
                this.$nextTick(_ => {
                    this.$refs.saveTagInput.$refs.input.focus();
                });
            },
            handleInputConfirm() {
                let inputValue = this.inputValue;

                if (inputValue && this.alternativeName.indexOf(inputValue) == -1) {
                    this.alternativeName.push(inputValue);
                    this.updateCompany();
                }
                this.inputVisible = false;
                this.inputValue = '';
            },
            updateCompany() {
                let self = this;
                self.loading = true;
                let uri = "company/update/"+self.companyId;
                let postData = {
                    alternativeName: self.alternativeName,
                    categoryIds: self.categoryIds};

                axios.put(uri,postData).then(function (data) {
                    self.loading = false;
                    self.getInfo();
                }).catch(function (error) {
                    self.loading = false;
                });
            },
            handleClose(tag) {
                console.log(tag);
                this.alternativeName.splice(this.alternativeName.indexOf(tag), 1);
                this.updateCompany();
            },
            handleSelect(item) {
                if (item && this.categoryIds.indexOf(item.id) == -1) {
                    this.categoryTags.push(item);
                    this.categoryIds.push(item.id);
                    this.updateCompany();
                }
                this.categoryName = '';
            },
            handleIndustryClose(tag) {
                this.categoryTags.splice(this.categoryTags.indexOf(tag), 1);
                this.categoryIds.splice(this.categoryIds.indexOf(tag.id),1);
                this.updateCompany();
            },
        },
        mounted() {
            this.search();
            this.queryIndustry();
            this.queryCompany();
            this.getInfo();
        },
        filters: {
            titleFormatter(title) {
                if (title.length >= 10) {
                    return title.substring(0, 10) + '...';
                }
                return title.length === 0 ? '--' : title;
            }
        }
    }
</script>

<style scoped>
    .card-toolbar .form-inline .form-group {
        display: block;
        margin-bottom: 15px;
    }
    .input-group-addon, .input-group-btn
    {
        width:100%;
    }
</style>
